<template>
  <div class="home" v-if="review_word_list.length > 0">
    <div class="img-body">
      <img v-if="isShow" :src="cur_word.images" alt />
    </div>

    <div class="btn-body">
      <button class="start" v-if="isStart===false" @click="start">开始</button>
      <template v-else>
        <button class="repeat" @click="repeat">重复</button>

        <template>
          <button
            v-if="!isShow"
            class="answer"
            ref="el_answer"
            @touchstart.prevent.stop="answer_start"
            @touchend="answer_end"
          ></button>
          <button v-else class="wrong" @click="wrong">下一个</button>
        </template>

        <button class="show" @click="isShow = true">展示</button>
      </template>
    </div>
  </div>
</template>

<script>
/* eslint-disable */
import axios from 'axios'
import Recorder from 'js-audio-recorder'
import { ResultReason } from 'microsoft-cognitiveservices-speech-sdk'

// const window.SpeechSDK = require('microsoft-cognitiveservices-speech-sdk')
const recorder = new Recorder({
  sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
  sampleRate: 24000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
  numChannels: 1 // 声道，支持 1 或 2， 默认是1
  // compiling: false,(0.x版本中生效,1.x增加中)  // 是否边录边转换，默认是false
})

// const speechConfig = window.SpeechSDK.SpeechConfig.fromAuthorizationToken(tokenObj.authToken, tokenObj.region)
// const speechConfig = window.SpeechSDK.SpeechConfig.fromSubscription('c0064f08da8947af92d24303fdbc441b', 'eastasia')
// speechConfig.speechRecognitionLanguage = 'zh-CN'
export default {
  name: 'ReviewPage',
  components: {
  },
  data () {
    return {
      index: 0,
      isStart: false,
      isShow: false,
      userInfo: {},
      all_word: JSON.parse(window.localStorage.getItem('all_word')),
      review_word_list: []
    }
  },
  computed: {
    cur_word() {
      return this.review_word_list.length > 0 ? this.review_word_list[this.index] : null
    }
  },
  async created () {
    await this.login()
    await this.getReview()
  },
  mounted() {
  },
  methods: {
    async login () {
      const { data: { data } } = await axios({
        url: process.env.VUE_APP_BASE_API + '/user/login?mobile=15503593230&sms_code=111'
      })
      this.userInfo = data
    },
    async getReview () {
      const { data: { data } } = await axios({
        url: process.env.VUE_APP_BASE_API + '/review/get_review'
      })

      this.review_word_list = data.map(item => {
        const word = this.all_word[item.wordId]
        return { ...word, ...item }
      })
    },
    // 基本功能 ----------------------------------------------------------
    start() {
      this.isStart = true
      this.playAudio()
    },
    next() {
      if (this.index + 1 >= this.review_word_list.length) {
        alert('结束！！！！')
        this.$router.push('/home')
        return
      }
      this.isShow = false
      this.index++
      this.playAudio()
    },
    playAudio() {
      this.$nextTick(() => {
        this.audio = new Audio(this.cur_word.audioWord)
        this.audio.playbackRate = 0.8
        setTimeout(()=>{
          this.audio.play()
        }, 500)
      })
    },
    repeat() {
        setTimeout(()=>{
          this.audio.play()
        }, 500)
    },
    async right() {
      await axios({
        method: 'patch',
        url: process.env.VUE_APP_BASE_API + `/review/update_review?id=${this.cur_word.id}&is_right=true`
      })
      this.next()
    },
    async wrong() {
      await axios({
        method: 'patch',
        url: process.env.VUE_APP_BASE_API + `/review/update_review?id=${this.cur_word.id}&is_right=false`
      })
      this.next()
    },
    answer_start() {
      this.$refs.el_answer.style.backgroundColor = 'red'
      recorder.start()
    },
    answer_end() {
      this.$refs.el_answer.style.backgroundColor = 'green'
      recorder.stop()
      const blob = recorder.getWAVBlob()
      const file = new File([blob], 'a.wav', { type: 'audio/wav' })

      if (this.cur_word.translate.length === 1) {
        this.speechScore(file)
      } else {
        this.speechRecognize(file)
      }
    },
    speechScore(file) {
      const pronunciationAssessmentConfig = new window.SpeechSDK.PronunciationAssessmentConfig(
        this.cur_word.translate,
        window.SpeechSDK.PronunciationAssessmentGradingSystem.HundredMark,
        window.SpeechSDK.PronunciationAssessmentGranularity.Phoneme,
        false)
      // pronunciationAssessmentConfig.enableProsodyAssessment()
      // pronunciationAssessmentConfig.enableContentAssessmentWithTopic('greeting')

      const audioConfig = window.SpeechSDK.AudioConfig.fromWavFileInput(file)
      window.speechConfig.speechRecognitionLanguage = 'zh-CN'
      const speechRecognizer = new window.SpeechSDK.SpeechRecognizer(window.speechConfig, audioConfig)

      pronunciationAssessmentConfig.applyTo(speechRecognizer)

      speechRecognizer.recognizeOnceAsync(res => {
        console.log(res)
        speechRecognizer.close()
        const str = res.properties.getProperty(window.SpeechSDK.PropertyId.SpeechServiceResponse_JsonResult)
        const obj = JSON.parse(str)
        const score = obj.NBest[0].PronunciationAssessment.PronScore

        if (score > 85) {
          this.$root.$children[0].answerRight()
          this.isShow = true
          setTimeout(() => {
            this.right()
          }, 1500)
        } else {
          this.$root.$children[0].answerWrong()
        }
      })
    },
    speechRecognize(file) {
      console.log(window.SpeechSDK);
      const audioConfig = window.SpeechSDK.AudioConfig.fromWavFileInput(file)
      window.speechConfig.speechRecognitionLanguage = 'zh-CN'
      const speechRecognizer = new window.SpeechSDK.SpeechRecognizer(window.speechConfig, audioConfig)

      speechRecognizer.recognizeOnceAsync(result => {
        console.log(result)
        speechRecognizer.close()
        if (result.privReason === ResultReason.RecognizedSpeech) {
          console.log(result.privText)
          this.sendGPT(result.privText.replace('。', ''))
        } else {
          console.log('9999999999999999')
        }
      })
    },
    async sendGPT(zh) {
      const { data: { code, data } } = await axios({
        url: 'http://ec2-13-115-105-115.ap-northeast-1.compute.amazonaws.com/gpt/translate',
        method: 'post',
        data: {
          en: this.cur_word.word,
          zh
        }
      })
      if (code === 10000) {
        if (data === '1') {
          this.$root.$children[0].answerRight()
          this.isShow = true
          setTimeout(() => {
            this.right()
          }, 1500)
        } else if (data === '2') {
          this.$root.$children[0].answerWrong()
        }
      }
    },
  }
}
</script>

<style lang="less" scoped>
.img-body {
  width: 100%;
  height: 60vh;
  margin: 2vw 0;
  display: flex;
  justify-content: center;
  img {
    max-width: 100%;
    max-height: 100%;
  }
}
.btn-body {
  display: flex;
  justify-content: space-around;
  align-items: center;
  button {
    width: 15vw;
    height: 8vw;
    border-radius: 2vw;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 4vw;
    color: #fff;
  }
  .start {
    background-color: green;
  }
  .right {
    background-color: green;
  }
  .wrong {
    background-color: rgb(220, 53, 69);
  }
  .repeat {
    background-color: hotpink;
  }
  .show {
    background-color: orange;
  }
  .remember {
    background-color: #666;
  }
}
</style>
